import pyaudio
import wave
import speech_recognition as sr

def start_audio(time=3, save_file="test_get.wav"):
    '''
    录制语音
    '''
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 16000
    RECORD_SECONDS = time  # 需要录制的时间
    WAVE_OUTPUT_FILENAME = save_file  # 保存的文件名

    p = pyaudio.PyAudio()  # 初始化
    print("ON")

    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)  # 创建录音文件
    frames = []

    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)  # 开始录音

    print("OFF")

    stream.stop_stream()
    stream.close()
    p.terminate()

    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')  # 保存
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()
    speech(WAVE_OUTPUT_FILENAME)

def speech(voice_file_path):
    r = sr.Recognizer()    #调用识别器
    test = sr.AudioFile(voice_file_path)   #导入语音文件
    with test as source:
        audio = r.record(source)
    type(audio)
    c=r.recognize_sphinx(audio, language='zh-cn')     #识别输出
    print(c)

start_audio(time=6)
